import os
from flask import Blueprint, render_template, request, jsonify, current_app, flash, redirect, url_for, send_file
from app.models import Video, Category
from app import db
from app.utils.qiniu_storage import delete_from_qiniu, upload_to_qiniu
import tempfile
import time
from werkzeug.utils import secure_filename

main = Blueprint('main', __name__)

@main.route('/')
def index():
    videos = Video.query.order_by(Video.created_at.desc()).all()
    base_domain = "https://jkl7n.lingbankeji.com"
    
    # 处理每个视频的URL
    processed_videos = []
    for video in videos:
        video_data = {
            'id': video.id,
            'title': video.title,
            'description': video.description,
            'status': video.status,
            'created_at': video.created_at,
            'category': video.category.name if video.category else '未分类'
        }
        
        # 处理封面URL - 移除可能重复的目录名
        cover_key = video.cover_url
        if cover_key.startswith(('http://', 'https://')):
            cover_key = cover_key.split('/')[-1]
        if cover_key.startswith('covers/'):
            cover_key = cover_key.replace('covers/', '')
        video_data['cover_url'] = f"{base_domain}/covers/{cover_key}"
        
        # 处理视频URL - 移除可能重复的目录名
        video_key = video.video_url
        if video_key.startswith(('http://', 'https://')):
            video_key = video_key.split('/')[-1]
        if video_key.startswith('videos/'):
            video_key = video_key.replace('videos/', '')
        video_data['video_url'] = f"{base_domain}/videos/{video_key}"
        
        # 获取视频类型
        ext = video_key.split('.')[-1].lower() if '.' in video_key else 'mp4'
        video_data['mime_type'] = get_mime_type(ext)
        
        processed_videos.append(video_data)
        
    return render_template('index.html', videos=processed_videos)

@main.route('/admin', methods=['GET', 'POST'])
def admin():
    if request.method == 'POST':
        try:
            # 获取表单数据
            title = request.form.get('title')
            category_id = request.form.get('category_id')
            description = request.form.get('description')
            cover_file = request.files.get('cover')
            video_file = request.files.get('video')

            # 验证必填字段
            if not all([title, category_id, cover_file, video_file]):
                return jsonify({
                    'success': False,
                    'error': '请填写所有必填字段'
                })

            # 使用临时文件处理上传
            cover_result = None
            video_result = None

            try:
                # 创建临时目录（如果不存在）
                temp_dir = os.path.join(current_app.instance_path, 'temp')
                os.makedirs(temp_dir, exist_ok=True)

                # 生成临时文件路径
                cover_temp_path = os.path.join(temp_dir, f'cover_{int(time.time())}_{secure_filename(cover_file.filename)}')
                video_temp_path = os.path.join(temp_dir, f'video_{int(time.time())}_{secure_filename(video_file.filename)}')

                # 保存文件到临时位置
                cover_file.save(cover_temp_path)
                video_file.save(video_temp_path)

                try:
                    # 上传到七牛云
                    cover_filename = f'covers/{int(time.time())}_{secure_filename(cover_file.filename)}'
                    video_filename = f'videos/{int(time.time())}_{secure_filename(video_file.filename)}'

                    cover_result = upload_to_qiniu(cover_temp_path, cover_filename)
                    video_result = upload_to_qiniu(video_temp_path, video_filename)

                    # 保存到数据库
                    video = Video(
                        title=title,
                        description=description,
                        category_id=category_id,
                        cover_url=cover_result['url'],
                        video_url=video_result['url'],
                        status='published'
                    )
                    db.session.add(video)
                    db.session.commit()

                    return jsonify({
                        'success': True,
                        'message': '上传成功',
                        'data': {
                            'id': video.id,
                            'title': video.title,
                            'cover_url': video.cover_url,
                            'video_url': video.video_url
                        }
                    })

                finally:
                    # 清理临时文件
                    try:
                        if os.path.exists(cover_temp_path):
                            os.remove(cover_temp_path)
                    except Exception as e:
                        current_app.logger.warning(f"删除临时封面文件失败: {str(e)}")

                    try:
                        if os.path.exists(video_temp_path):
                            os.remove(video_temp_path)
                    except Exception as e:
                        current_app.logger.warning(f"删除临时视频文件失败: {str(e)}")

            except Exception as e:
                # 如果上传过程中出错，回滚数据库
                db.session.rollback()
                current_app.logger.error(f"上传失败: {str(e)}")
                return jsonify({
                    'success': False,
                    'error': f'上传失败：{str(e)}'
                }), 500

        except Exception as e:
            current_app.logger.error(f"请求处理失败: {str(e)}")
            return jsonify({
                'success': False,
                'error': f'系统错误：{str(e)}'
            }), 500

    # GET 请求返回页面
    categories = Category.query.all()
    videos = Video.query.order_by(Video.created_at.desc()).all()
    return render_template('admin.html', categories=categories, videos=videos)

@main.route('/video/<int:video_id>/preview')
def preview_video(video_id):
    try:
        video = Video.query.get_or_404(video_id)
        
        # 构建完整的视频和封面URL
        video_key = video.video_url
        cover_key = video.cover_url
        base_domain = "https://jkl7n.lingbankeji.com"
        
        # 处理视频URL - 移除可能重复的目录名
        if video_key.startswith(('http://', 'https://')):
            video_key = video_key.split('/')[-1]
        if video_key.startswith('videos/'):
            video_key = video_key.replace('videos/', '')
        video_url = f"{base_domain}/videos/{video_key}"
        
        # 处理封面URL - 移除可能重复的目录名
        if cover_key.startswith(('http://', 'https://')):
            cover_key = cover_key.split('/')[-1]
        if cover_key.startswith('covers/'):
            cover_key = cover_key.replace('covers/', '')
        cover_url = f"{base_domain}/covers/{cover_key}"
            
        current_app.logger.info(f"视频URL: {video_url}")
        current_app.logger.info(f"封面URL: {cover_url}")
        
        # 获取文件扩展名
        ext = video_key.split('.')[-1].lower() if '.' in video_key else 'mp4'
        
        # 添加时间戳防止缓存
        video_url = f"{video_url}?t={int(time.time())}"
        cover_url = f"{cover_url}?t={int(time.time())}"
        
        return jsonify({
            'success': True,
            'video_url': video_url,
            'cover_url': cover_url,
            'title': video.title,
            'mime_type': get_mime_type(ext),
            'download_url': video_url
        })
    except Exception as e:
        current_app.logger.error(f"获取视频信息失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': '获取视频信息失败'
        }), 500

def get_mime_type(ext):
    """根据文件扩展名获取 MIME 类型"""
    mime_types = {
        'mp4': 'video/mp4',
        'mov': 'video/quicktime',
        'avi': 'video/x-msvideo',
        'wmv': 'video/x-ms-wmv',
        'flv': 'video/x-flv',
        'webm': 'video/webm',
        'm3u8': 'application/x-mpegURL'
    }
    return mime_types.get(ext.lower(), 'video/mp4')

@main.route('/video/<int:video_id>', methods=['DELETE'])
def delete_video(video_id):
    try:
        video = Video.query.get_or_404(video_id)
        
        # 从七牛云删除文件
        delete_success = True
        if video.cover_url:
            # video.cover_url 现在存储的是文件的 key
            if not delete_from_qiniu(video.cover_url):
                current_app.logger.warning(f"删除封面文件失败: {video.cover_url}")
                delete_success = False
                
        if video.video_url:
            # video.video_url 现在存储的是文件的 key
            if not delete_from_qiniu(video.video_url):
                current_app.logger.warning(f"删除视频文件失败: {video.video_url}")
                delete_success = False
        
        # 从数据库删除记录
        db.session.delete(video)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '视频删除成功' if delete_success else '视频记录已删除，但云存储文件删除可能不完整',
            'delete_success': delete_success
        })
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除视频失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'删除失败：{str(e)}'
        }), 500 

@main.route('/upload', methods=['POST'])
def upload():
    """通用文件上传接口"""
    try:
        # 检查是否有文件
        if 'file' not in request.files:
            return jsonify({'error': '没有文件被上传'}), 400
            
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
            
        # 获取其他表单数据
        title = request.form.get('title')
        category = request.form.get('category')
        
        if not title or not category:
            return jsonify({'error': '标题和分类不能为空'}), 400
            
        # 使用临时文件处理上传
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            file.save(temp_file.name)
            try:
                # 生成唯一的文件名
                filename = f"{int(time.time())}_{secure_filename(file.filename)}"
                result = upload_to_qiniu(temp_file.name, filename)
                
                return jsonify({
                    'success': True,
                    'url': result['url'],
                    'key': result['key']
                })
            finally:
                # 确保清理临时文件
                if os.path.exists(temp_file.name):
                    os.unlink(temp_file.name)
            
    except Exception as e:
        current_app.logger.error(f"文件上传失败: {str(e)}")
        return jsonify({'error': str(e)}), 500 